package com.jianwei.configuration;

import com.zaxxer.hikari.HikariDataSource;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Random;

/**
 * @author wjwei
 */
public class DynamicDataSource {

    private final List<HikariDataSource> hikariDataSourceList;
    /** 同一个线程共用一个数据库连接*/
    private static final ThreadLocal<Connection> CONNECTION_THREAD_LOCAL = new ThreadLocal<>();

    public DynamicDataSource(List<HikariDataSource> hikariDataSourceList) {
        this.hikariDataSourceList = hikariDataSourceList;
    }

    public Connection getConnection() throws SQLException {
        Connection connection = CONNECTION_THREAD_LOCAL.get();
        if (connection != null) {
            return connection;
        }
        connection = hikariDataSourceList.get(new Random().nextInt(hikariDataSourceList.size())).getConnection();
        // 设置隔离级别为RC
        connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        CONNECTION_THREAD_LOCAL.set(connection);
        return connection;
    }

    public void releaseConnection() throws SQLException {
        final Connection connection = CONNECTION_THREAD_LOCAL.get();
        if (connection != null) {
            CONNECTION_THREAD_LOCAL.remove();
            connection.close();
        }
    }
}
